package com.adopapa.ethexplorer.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.adopapa.ethexplorer.domain.UserInfo;
import com.adopapa.ethexplorer.utils.Tools;

@Service
public class UserInfoService extends BaseService {

	@Autowired
	private UserInfoRepository userInfoRepository;
	
	public UserInfo getUserInfoById(String id) {
		Optional<UserInfo> optional = userInfoRepository.findById(id);
		return optional.isPresent() ? optional.get() : null;
	}

	public UserInfo getUserInfoByLoginName(String loginName) {
		List<UserInfo> results = userInfoRepository.findByLoginName(loginName);
		return Tools.empty(results) ? null : results.get(0);
	}
	
	public UserInfo getUserInfoByAddress(String address) {
		List<UserInfo> results = userInfoRepository.getUserInfoByAddress(address);
		return Tools.empty(results) ? null : results.get(0);
	}

	public Page<UserInfo> getUserInfoPage(int pageNo, int pageSize, UserInfo usrInfo) {
		PageRequest pageRequest = QueryHelper.buildPageRequest(pageNo, pageSize, Order.desc("createTime"));
		Specification<UserInfo> specification = QueryHelper.buildSpecification(usrInfo);
		Page<UserInfo> page = userInfoRepository.findAll(specification, pageRequest);
		return page;
	}

	public UserInfo saveUserInfo(UserInfo userInfo) {
		return userInfoRepository.saveAndFlush(userInfo);
	}

	public void deleteUserInfo(String id) {
		userInfoRepository.deleteById(id);
	}

	public void deleteUserInfo(UserInfo userInfo) {
		userInfoRepository.delete(userInfo);
	}

}
